package com.wyj.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.google.common.collect.Maps;
import com.wyj.common.LogPortal;
import com.wyj.dto.data.UserGlobalData;
import com.wyj.service.UserGlobalDataService;
import com.wyj.utils.ErrorUtils;
import com.wyj.utils.SystemConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author ：wyj
 * @description：TODO
 * @date ：2024/3/7 11:24 PM
 */
@Service
public class UserGlobalDataServiceImpl implements UserGlobalDataService {

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public UserGlobalData getUserGlobalDataByUuid(String uuid) {
        String globalKey = getUserGlobalKey(uuid);
        BoundHashOperations<String, String, Object> ops = redisTemplate.boundHashOps(globalKey);
        Map<String, Object> entries = ops.entries();
        if (entries == null || entries.isEmpty()) {
            // TODO 从S3当中进行读取
        }
        if (entries == null) {
            entries = Maps.newHashMap();
        }
        UserGlobalData globalData = null;
        try {
            globalData = BeanUtil.fillBeanWithMap(entries, new UserGlobalData(), false);
        } catch (Exception e) {
            LogPortal.error(getClass().getSimpleName() + " userGlobalData transform error!!");
            ErrorUtils.sendErrorMessage(e, "userGlobalData transform error!!");
            throw e;
        }
        return globalData;
    }

    @Override
    public void saveUserGlobalData(UserGlobalData globalData, String uuid) {
        // 1.删缓存
        String globalKey = getUserGlobalKey(uuid);
        BoundHashOperations<String, String, Object> ops = redisTemplate.boundHashOps(globalKey);
        ops.entries().clear();
        // 2.存入新的data
        Map<String, Object> map = BeanUtil.beanToMap(globalData);
        ops.putAll(map);
        // 3.更新S3的持久化数据

    }

    private String getUserGlobalKey(String uuid) {
        return SystemConstants.USER_GLOBAL_DATA_PRE + uuid;
    }

}
